		.text

SPMCR = 0x37

; void write_page (unsigned int adr, unsigned char function);
_write_page::

		MOV R31,R17        
        MOV R30,R16         ;move adress to z pointer (R31=ZH R30=ZL)
        OUT SPMCR,R18       ;argument 2 decides function
        SPM                 ;perform pagewrite
		.dw $ffff
		NOP
        RET

; void fill_temp_buffer (unsigned int data, unsigned int adr);
_fill_temp_buffer::


        MOV R31,R19        
        MOV R30,R18         ;move adress to z pointer (R31=ZH R30=ZL)
        MOV R1,R17
        MOV R0,R16          ;move data to reg 0 and 1      
        LDI R18,0x01
        OUT SPMCR,R18
        SPM            ;Store program memory
        RET      

;unsigned int read_program_memory (unsigned int adr ,unsigned char cmd);
_read_program_memory::
        
        MOV R31,R17         ;R31=ZH R30=ZL
        MOV R30,R16         ;move adress to z pointer
        SBRC R18,0          ;read lockbits? (second argument=0x09)
        OUT SPMCR,R18	    ;if so, place second argument in SPMEN register
        LPM                 ;read LSB
        MOV R16,R0         
        INC R30
        LPM
        MOV R17,R0          ;read MSB (ignored when reading lockbits)
        RET

;void write_lock_bits (unsigned char val);
_write_lock_bits::

        MOV R0,R16   
        LDI R17,0x09     
        OUT SPMCR,R17
        SPM                ;write lockbits
		.dw $ffff
		NOP
        RET